package com.xtianzhuang.www.controller.project;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.xtianzhuang.www.annotation.Log;
import com.xtianzhuang.www.annotation.Log.LogType;
import com.xtianzhuang.www.controller.BaseController;
import com.xtianzhuang.www.entity.TdPProject;
import com.xtianzhuang.www.entity.TdPProjectExample;
import com.xtianzhuang.www.entity.TfUUser;
import com.xtianzhuang.www.entity.VInterfaceParam;
import com.xtianzhuang.www.entity.VInterfaceParamExample;
import com.xtianzhuang.www.entity.VProjectIntf;
import com.xtianzhuang.www.entity.VProjectIntfExample;
import com.xtianzhuang.www.entity.constants.CodeConstants;
import com.xtianzhuang.www.entity.constants.IsDeletedConstants;
import com.xtianzhuang.www.entity.others.ProjectInterfaceExport;
import com.xtianzhuang.www.entity.request.GetInputParamRequest;
import com.xtianzhuang.www.entity.request.GetParamTreeRequest;
import com.xtianzhuang.www.entity.request.ProjectDoucumentGetRequest;
import com.xtianzhuang.www.entity.request.ProjectListExportRequest;
import com.xtianzhuang.www.entity.request.ProjectListRequest;
import com.xtianzhuang.www.entity.request.base.BaseRequest;
import com.xtianzhuang.www.entity.response.GetInputParamResponse;
import com.xtianzhuang.www.entity.response.GetParamTreeResponse;
import com.xtianzhuang.www.entity.response.ProjectDoucumentGetResponse;
import com.xtianzhuang.www.entity.response.ProjectListResponse;
import com.xtianzhuang.www.entity.response.base.BaseResponse;
import com.xtianzhuang.www.utils.PageData;
import com.xtianzhuang.www.utils.WordGenerator;

/**
 * 
 * @author xtian.zhuang
 * @date Jul 22, 2019
 */
@Controller
@RequestMapping("/project")
public class ProjectController extends BaseController {

	@RequestMapping(value = "/project-list")
	public ModelAndView projectList(BaseRequest request, BaseResponse response) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("project/project-list");
		super.executeBase(request, response);
		modelAndView.addObject("res", response);
		// 跳回原地址
		return modelAndView;
	}

	@RequestMapping(value = "/project-param-list")
	public ModelAndView projectParamList(BaseRequest request, BaseResponse response) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("project/project--param-list");
		super.executeBase(request, response);
		modelAndView.addObject("res", response);
		// 跳回原地址
		return modelAndView;
	}

	@RequestMapping("/projectList")
	@ResponseBody
	@Log(type = LogType.PROJECT)
	public ProjectListResponse projectList(ProjectListRequest request) {
		ProjectListResponse response = new ProjectListResponse();
		TdPProjectExample example = new TdPProjectExample();
		example.setOffset(request.getOffset());
		example.setLimit(request.getLimit());
		PageData<TdPProject> data = commonServiceBiz.getPageData(example);
		response.setCode(CodeConstants.SUCCESS);
		response.setData(data.getData());
		response.setTotal(data.getTotal());
		return response;

	}


	@RequestMapping("/getInputParam")
	@ResponseBody
	@Log(type = LogType.PROJECT)
	public GetInputParamResponse getInputParam(GetInputParamRequest request) {
		GetInputParamResponse response = new GetInputParamResponse();
		String input = projectServiceBiz.getInput(request.getInterfaceId());
		response.setInput(input);
		response.setCode(CodeConstants.SUCCESS);
		response.setMessage("生成成功");
		return response;

	}

	@RequestMapping("/getParamTree")
	@ResponseBody
	@Log(type = LogType.PROJECT)
	public GetParamTreeResponse getParamTree(GetParamTreeRequest request) {
		GetParamTreeResponse response = new GetParamTreeResponse();
		JSONArray input = projectServiceBiz.getParamTree(request.getInterfaceId());
		response.setData(input);
		response.setCode(CodeConstants.SUCCESS);
		response.setMessage("生成成功");
		return response;

	}



	@RequestMapping("/projectDetail")
	@Log(type = LogType.PROJECT)
	@RequiresRoles(value = {"admin", "developer", "tester"}, logical = Logical.OR)
	public ModelAndView projectDetail(Integer projectId, BaseRequest request, BaseResponse response) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("project/project-detail");
		modelAndView.addObject("projectId", projectId);
		super.executeBase(request, response);
		modelAndView.addObject("res", response);
		return modelAndView;

	}

	@RequestMapping("/getProjectDoucument")
	@Log(type = LogType.PROJECT)
	@RequiresRoles(value = {"admin", "developer"}, logical = Logical.OR)
	@ResponseBody
	public ProjectDoucumentGetResponse getProjectDoucument(ProjectDoucumentGetRequest request,
			HttpServletRequest httpServletRequest) {
		ProjectDoucumentGetResponse response = new ProjectDoucumentGetResponse();
		// 获取项目
		TdPProject tdPProject = projectServiceBiz.selectTdPProjectByProjectId(request.getProjectId());
		VProjectIntfExample example = new VProjectIntfExample();
		example.or().andProjectIdEqualTo(request.getProjectId());
		example.setOrderByClause("show_order asc,interface_id asc");
		// 获取项目接口
		PageData<VProjectIntf> data = commonServiceBiz.getPageData(example);
		// 准备文件夹,获取项目中document文件夹的路径
		String parentDir = httpServletRequest.getServletContext().getRealPath("document");
		logger.error("parentDir is "+parentDir);
		try {
			projectServiceBiz.checkDir(parentDir);
			String projectDir = parentDir + "/" + tdPProject.getProjectName();
			projectServiceBiz.checkDir(projectDir);
			// 生成项目接口页面
			projectServiceBiz.getProjectInterfaceDocument(projectDir, tdPProject, data);
			// 生成接口参数页面 下划线格式
			String  nlptDir = projectDir + "/nlpt"  ;
			projectServiceBiz.checkDir(nlptDir);
			projectServiceBiz.getInterfaceParamsDocument(nlptDir, tdPProject, data,"1");
			// 生成接口参数页面 正常格式
			String  commonDir = projectDir + "/common"  ;
			projectServiceBiz.checkDir(commonDir);
			projectServiceBiz.getInterfaceParamsDocument(commonDir, tdPProject, data,"0");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		response.setCode(CodeConstants.SUCCESS);
		response.setMessage("生成成功");
		return response;
	}

	@RequestMapping("/addTask")
	@Log(type = LogType.PROJECT)
	public ModelAndView addTask(BaseRequest request, BaseResponse response) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("project/project-addTask");
		List<TfUUser> developers = userServiceBiz.getDeveloperUser();
		List<TdPProject> projects = projectServiceBiz.getProjectList();
		modelAndView.addObject("developers", developers);
		modelAndView.addObject("projects", projects);
		super.executeBase(request, response);
		modelAndView.addObject("res", response);
		return modelAndView;
	}

	@RequestMapping(value = "projectListExport", method = {RequestMethod.GET, RequestMethod.POST})
	public void projectListExport(ProjectListExportRequest request, Model model, HttpServletRequest req, HttpServletResponse resp)
	{
		try {
			req.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		// 通过循环将表单参数放入
		TdPProject tdPProject = projectServiceBiz.selectTdPProjectByProjectId(request.getProjectId());
		VProjectIntfExample example = new VProjectIntfExample();
		example.or().andIsDeletedEqualTo(IsDeletedConstants.IN_USE);
		example.setOrderByClause("show_order asc");
		List<VProjectIntf> list = projectServiceBiz.projetDetailQuery(example);
		List<ProjectInterfaceExport> exportList = new ArrayList<ProjectInterfaceExport>();
		for (VProjectIntf vProjectIntf : list) {
			ProjectInterfaceExport itemExport = new ProjectInterfaceExport();
			itemExport.setVprojectIntf(vProjectIntf);
			VInterfaceParamExample example2 = new VInterfaceParamExample();
			List<VInterfaceParam> list2 = projectServiceBiz.interfaceParamsQuery(example2);
			itemExport.setParamlist(list2);
			exportList.add(itemExport);
		}
		ServletOutputStream out = null;
		try {
			// 调用工具类WordGenerator的createDoc方法生成Word文档
			byte[] content = WordGenerator.createWord(exportList, "resume", tdPProject.getProjectName());
			ByteArrayInputStream bais = new ByteArrayInputStream(content);
			resp.setCharacterEncoding("utf-8");
			resp.setContentType("application/msword");
			// 设置浏览器以下载的方式处理该文件默认名为resume.doc
			String fileName = tdPProject.getProjectName();
			resp.addHeader("Content-Disposition",
					"attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1") + ".doc");

			out = resp.getOutputStream();
			byte[] buffer = new byte[512]; // 缓冲区
			int bytesToRead = -1;
			// 通过循环将读入的Word文件的内容输出到浏览器中
			while ((bytesToRead = bais.read(buffer)) != -1) {
				out.write(buffer, 0, bytesToRead);
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (out != null) try {
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}
